package com.kkd.kkdapp.activity;

import java.text.DecimalFormat;

import org.json.JSONException;
import org.json.JSONObject;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.http.entity.CurrentTenderSuccessEntity;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.AuthenticationUtils;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;
import com.kkd.kkdapp.view.EditText.FinanceEditText;
import com.kkd.kkdapp.view.EditText.FinanceEditText.onFinanceEditListener;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

/**
 * 天天赚购买
 * 
 * @author mty
 * 
 */
public class EveryDayTenderActivity extends BaseActivity implements
		OnClickListener {

	private static final int DECIMAL_DIGITS = 2; // 输入框小数的位数

	private final int SUBSCRIPTIONCODE_ZERO = 1; // 认购code = 0;
	private final int SUBSCRIPTIONCODE_ELSE = 2; // 认购code = 其它;

	private RelativeLayout mReturn; // 返回
	private Button next_bt; // 下一步
	private FinanceEditText invest_ed; // 投标金额
	private String title; // 标题
	// private String version; // 当前App版本号
	private TextView balance_tv1;
	private TextView recharge; // 充值
	private TextView name_tv;
	private String surplus; // 剩余金额
	private TextView allotted;
	private double balance;
	private boolean FALG = false;
	private boolean SUBMITFLAG = true;
	private String yuebaoid;
	private long lowestAmount;
	private String interests;
	private TextView rise_tv;
	private TextView hint;
	private TextView procedure_tv1;
	private double rates;
	private TextView predictdayearnings_tv;
	DecimalFormat df = new DecimalFormat("0.01");
	DecimalFormat df1 = new DecimalFormat("###,##0.01");
	private Dialog mDialog;
	private String bmouts;
	private String yuebaoDesc;
	private String infoDesc;
	private boolean distinguish;
	private Dialog nsfDialog; // 账户余额不足对话框
	private Dialog dialog;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			String product = "";
			switch (msg.what) {
			case SUBSCRIPTIONCODE_ZERO:
				next_bt.setEnabled(true);
				FALG = true;
				dialog.dismiss();
				CurrentTenderSuccessEntity dataCurrentTenderSuccessEntity = (CurrentTenderSuccessEntity) msg.obj;
				if (!"".equals(title)) {
					product = title;
				} else {
					product = "天天赚";
				}
				distinguish = true;
				showDialog(EveryDayTenderActivity.this, product, invest_ed
						.getText().toString(), predictdayearnings_tv.getText()
						.toString(),
						dataCurrentTenderSuccessEntity.getStartInterest(),
						dataCurrentTenderSuccessEntity.getIncomeTime());
				// showDialog(R.drawable.tenderresult_succeed, promp, product,
				// df1.format(Double.parseDouble(invest_ed.getText()
				// .toString())), "返回", false);
				break;
			case SUBSCRIPTIONCODE_ELSE:
				next_bt.setEnabled(true);
				FALG = true;
				dialog.dismiss();
				String desc = (String) msg.obj;
				if (!"".equals(title)) {
					product = title;
				} else {
					product = "天天赚";
				}
				distinguish = false;
				showDialog(R.drawable.tenderresult_succeed_bedefeated, desc,
						product, df1.format(Double.parseDouble(invest_ed
								.getText().toString())), "重新认购", true);
				break;
			case 4:
				balance_tv1.setText("" + bmouts);
				hint.setText(yuebaoDesc);
				break;
			case 5:
				infoDesc = (String) msg.obj;
				// showToast(infoDesc);
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_every_day_tender);
		Intent intent = getIntent();
		title = intent.getStringExtra("title");
		surplus = intent.getStringExtra("surplus");
		yuebaoid = intent.getStringExtra("yuebaoid");
		lowestAmount = intent.getLongExtra("lowestAmount", 0);
		interests = intent.getStringExtra("interests");
		rates = intent.getDoubleExtra("rates", 0);
		initUI();

	}

	/****************** 认购结果 ******************/

	protected void showDialog(Context context, String product, String amount,
			String rishouyi, String beginJiXi, String time2shouyi) {
		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		mDialog = DialogUtils.subscriptionResultsDialog2(
				EveryDayTenderActivity.this, product, amount, rishouyi,
				beginJiXi, time2shouyi, new OnClickListener() {

					@Override
					public void onClick(View view) {
						switch (view.getId()) {
						case R.id.finish_currenttender_result:
							if (mDialog != null) {
								mDialog.dismiss();
							}
							break;

						case R.id.textView_seeMyCurrent_currenttender_result:
							Intent intent = new Intent(
									EveryDayTenderActivity.this,
									AccountEverydayActivity.class);
							startActivity(intent);
							if (mDialog != null) {
								mDialog.dismiss();
							}
							break;

						default:
							break;
						}
					}
				});
		mDialog.show();
	}

	protected void showDialog(int imgID, String promp, String product,
			String amount, String bt_tv, boolean viewflag) {
		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		mDialog = DialogUtils.subscriptionResultsDialog(
				EveryDayTenderActivity.this, imgID, promp, product, amount,
				bt_tv, viewflag, new OnClickListener() {

					@Override
					public void onClick(View v) {
						switch (v.getId()) {
						case R.id.return_bt:
							mDialog.dismiss();
							if (distinguish) {
								finish();
							}
							break;
						case R.id.result_title_img:
							mDialog.dismiss();
							if (distinguish) {
								finish();
							}
							break;
						}
					}
				});
		mDialog.show();
	}

	/**
	 * 初始化组件
	 */
	public void initUI() {
		mReturn = (RelativeLayout) this.findViewById(R.id.everydaty_title_img);
		mReturn.setOnClickListener(this);
		next_bt = (Button) this.findViewById(R.id.next_bt);
		next_bt.setOnClickListener(this);

		recharge = (TextView) this.findViewById(R.id.recharge);
		recharge.setOnClickListener(this);
		balance_tv1 = (TextView) this.findViewById(R.id.balance_tv1);
		name_tv = (TextView) this.findViewById(R.id.name_tv);
		if (!TextUtils.isEmpty(title)) {
			name_tv.setText(title);
		} else {
			name_tv.setText("天天赚");
		}
		allotted = (TextView) this.findViewById(R.id.allotted);
		allotted.setText(surplus + "（元）");
		rise_tv = (TextView) this.findViewById(R.id.rise_tv);
		rise_tv.setText("起投金额：" + lowestAmount / 100 + "元");
		hint = (TextView) this.findViewById(R.id.hint);
		procedure_tv1 = (TextView) this.findViewById(R.id.procedure_tv1);
		procedure_tv1.setText("年利率：" + interests + "%");
		predictdayearnings_tv = (TextView) this
				.findViewById(R.id.predictdayearnings_tv);

		invest_ed = (FinanceEditText) this.findViewById(R.id.evinvest_ed);
		invest_ed.setHint("不得低于" + lowestAmount / 100 + "元");
		double limit = 10000;
		try {
			limit = Double.parseDouble(surplus);
		} catch (Exception e) {
			// 忽略
		}
		invest_ed.setLimitMax(limit);
		invest_ed.setDecimalDigits(DECIMAL_DIGITS);
		invest_ed.setFinanceEditListener(new onFinanceEditListener() {

			@Override
			public void onValueChanged(double toValue, double fromValue) {
				if (toValue > 0) {
					next_bt.setEnabled(true);
					FALG = true;
				} else {
					next_bt.setEnabled(false);
					FALG = false;
				}
			}

			@Override
			public void onOutLimit() {

			}

			@Override
			public void afterValueChanged(double toValue) {
				if (toValue > 0) {
					String ratess = df
							.format((int) ((toValue * rates) * 100) * 0.01);
					predictdayearnings_tv.setText(ratess);
				} else {
					predictdayearnings_tv.setText("0.00");
				}
			}
		});

		invest_ed.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_DONE) {
					SystemUtils.hideKeyBoard(EveryDayTenderActivity.this);
					if (SUBMITFLAG) {
						SUBMITFLAG = false;
						mHandler.postDelayed(new Runnable() {

							@Override
							public void run() {
								SUBMITFLAG = true;
							}
						}, 2000);
						if (FALG) {
							if (Double.parseDouble(invest_ed.getText()
									.toString()) <= balance) {
								if (Double.parseDouble(invest_ed.getText()
										.toString()) >= 50) {
									requestEveryDayTender();
								} else {
									showToast(R.string.astrict);
								}
							} else {
								if (nsfDialog != null) {
									nsfDialog.cancel();
									nsfDialog = null;
								}
								nsfDialog = DialogUtils
										.notSufficientFundsDialog(
												EveryDayTenderActivity.this,
												new OnClickListener() {

													@Override
													public void onClick(View v) {
														switch (v.getId()) {
														case R.id.cancel_tv: // 取消
															nsfDialog.dismiss();
															break;
														case R.id.recharge_tv: // 充值
															AuthenticationUtils
																	.getAuthenticationResult(
																			EveryDayTenderActivity.this,
																			3,
																			RechargeActivity.class);
															nsfDialog.dismiss();
															break;
														}

													}
												}, false);
								nsfDialog.show();
							}
						}
					}
					return true;
				}
				return false;
			}
		});

	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.next_bt: // 下一步
			if (SUBMITFLAG) {
				SUBMITFLAG = false;
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						SUBMITFLAG = true;
					}
				}, 0);
				if (FALG) {
					if (Double.parseDouble(invest_ed.getText().toString()) <= balance) {
						if (Double.parseDouble(invest_ed.getText().toString()) >= 50) {
							requestEveryDayTender();
						} else {
							showToast(R.string.astrict);
						}
					} else {
						if (nsfDialog != null) {
							nsfDialog.cancel();
							nsfDialog = null;
						}
						nsfDialog = DialogUtils.notSufficientFundsDialog(this,
								new OnClickListener() {

									@Override
									public void onClick(View v) {
										switch (v.getId()) {
										case R.id.cancel_tv: // 取消
											nsfDialog.dismiss();
											break;
										case R.id.recharge_tv: // 充值
											AuthenticationUtils
													.getAuthenticationResult(
															EveryDayTenderActivity.this,
															3,
															RechargeActivity.class);
											nsfDialog.dismiss();
											break;
										}

									}
								}, false);
						nsfDialog.show();
					}
				}
			}
			break;
		case R.id.everydaty_title_img: // 后退
			finish();
			break;
		case R.id.recharge:
			if (AppUtil.isConnect(this)) {
				if (PreferenceUtils.getInstance().getAutonym(this) == 1) {
					if (PreferenceUtils.getInstance().getBoundBankCard(this) == 1) {
						intent = new Intent(this, RechargeActivity.class);
						startActivity(intent);
					} else {
						intent = new Intent(this, ForTenderActivity.class);
						intent.putExtra("enterTypeFlag", 0);
						startActivity(intent);
					}
				} else {
					intent = new Intent(this, ForTenderActivity.class);
					intent.putExtra("enterTypeFlag", 4);
					startActivity(intent);
				}
			} else {
				showToast(R.string.network_anomaly);
			}
			break;
		}
	}

	/**
	 * 天天赚认购
	 */
	public void requestEveryDayTender() {
		next_bt.setEnabled(false);
		FALG = false;
		dialog = DialogUtils.tendertoLoadDialog(
				this,
				"认购金额 "
						+ (df.format(Double.parseDouble(invest_ed.getText()
								.toString()))) + "元", "正在认购,请稍候...");
		dialog.show();

		KkdHttpMagager.getInstance()
				.getEveryDayTenderManager(
						yuebaoid,
						(long) (Double.parseDouble(invest_ed.getText()
								.toString()) * 100), new HttpCallBack() {

							@Override
							public void onSuccess(int statusCode,
									Object responseBody) {
								CurrentTenderSuccessEntity currentTenderSuccessEntity = (CurrentTenderSuccessEntity) responseBody;
								Message msg = new Message();
								msg.obj = currentTenderSuccessEntity;
								msg.what = SUBSCRIPTIONCODE_ZERO;
								mHandler.sendMessage(msg);
							}

							@Override
							public void onFailure(int statusCode, String desc) {
								Message msg = new Message();
								msg.obj = desc;
								msg.what = SUBSCRIPTIONCODE_ELSE;
								mHandler.sendMessage(msg);
							}
						});
	}

	@Override
	protected void onStart() {
		super.onStart();
		getAccountInfo();
	}

	/**
	 * 
	 * 查询账户余额
	 */
	public void getAccountInfo() {
		String customerIdAndToken = PreferenceUtils.getInstance()
				.getcustomerId(this);
		String[] cat = customerIdAndToken.split("&");
		if(cat==null||cat.length<2)
			return;
		KkdHttpMagager.getInstance().getAccountInfoManager( String.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						String responseString = responseBody.toString();
						try {
							JSONObject data = new JSONObject(responseString);
							DecimalFormat df = new DecimalFormat("0.00");
							balance = data.getDouble("balance");
							bmouts = df.format(balance);
							yuebaoDesc = data.getString("yuebaoDesc");
							mHandler.sendEmptyMessage(4);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = new Message();
						msg.what = 5;
						msg.obj = desc;
						mHandler.sendEmptyMessage(5);
					}
				});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		/****** 账户余额不足对话框 ************/
		if (nsfDialog != null) {
			nsfDialog.cancel();
			nsfDialog = null;
		}
		if (dialog != null) {
			dialog.cancel();
			dialog = null;
		}
	}

}
